package com.huan.quartz.service.impl;

import com.huan.quartz.domain.QuartzJobCfg;
import com.huan.quartz.exception.QuartzJobException;
import com.huan.quartz.quartz.QuartzService;
import com.huan.quartz.repository.QuartzJobCfgRepository;
import com.huan.quartz.service.QuartzJobCfgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * quartz job service impl
 *
 * @author huan.fu
 * @date 2018/9/10 - 15:04
 */
@Service
public class QuartzJobCfgServiceImpl implements QuartzJobCfgService {

	@Autowired
	private QuartzJobCfgRepository quartzJobCfgRepository;
	@Autowired
	private QuartzService quartzService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addJob(QuartzJobCfg jobCfg) {
		quartzJobCfgRepository.save(jobCfg);
		quartzService.addQuartzJob(jobCfg);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateJob(QuartzJobCfg jobCfg) {
		quartzJobCfgRepository.save(jobCfg);
		quartzService.updateQuartzJob(jobCfg);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteJob(Long id) {
		QuartzJobCfg jobCfg = quartzJobCfgRepository.findOne(id);
		quartzJobCfgRepository.delete(jobCfg);
		quartzService.deleteQuartzJob(jobCfg);

	}

	@Override
	public List<QuartzJobCfg> queryAllEnableJobCfgs() {
		return quartzJobCfgRepository.findByJobStatus("1");
	}

	@Override
	public List<QuartzJobCfg> findAll() {
		return quartzJobCfgRepository.findAll();
	}

	@Override
	public QuartzJobCfg selectOne(Long id) {
		return quartzJobCfgRepository.findOne(id);
	}

	@Override
	public void updateQuartzExecuteClass(byte[] bytes, Long id) {
		QuartzJobCfg cfg = selectOne(id);
		if (null == cfg) {
			throw new QuartzJobException("[" + id + "]对应的job在数据库中不存在");
		}
		quartzService.updateQuartzJobExecuteClass(bytes,cfg);
	}
}
